package com.example.smartagrisys.util;

import com.example.smartagrisys.entity.User;
import com.example.smartagrisys.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * 安全工具类
 */
@Component
public class SecurityUtil {

    @Resource
    private UserService userService;

    @Resource
    private JwtUtil jwtUtil;

    private static UserService staticUserService;
    private static JwtUtil staticJwtUtil;

    @PostConstruct
    public void init() {
        staticUserService = userService;
        staticJwtUtil = jwtUtil;
    }

    /**
     * 获取当前登录用户
     * @return 当前登录用户
     */
    public static User getCurrentUser() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = getTokenFromRequest(request);
        if (token == null) {
            return null;
        }
        
        String username = staticJwtUtil.getUsernameFromToken(token);
        if (username == null) {
            return null;
        }
        
        return staticUserService.findByUsername(username);
    }

    /**
     * 获取当前登录用户ID
     * @return 当前登录用户ID
     */
    public static Long getCurrentUserId() {
        User user = getCurrentUser();
        return user != null ? user.getId() : null;
    }
    
    /**
     * 从请求中获取token
     * @param request 请求
     * @return token
     */
    private static String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }

    /**
     * 获取当前用户的角色
     *
     * @return 用户角色
     */
    public static String getCurrentUserRole() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = getTokenFromRequest(request);
            if (token == null) {
                return null;
            }
            
            return staticJwtUtil.getRoleFromToken(token);
        } catch (Exception e) {
            System.err.println("获取当前用户角色失败: " + e.getMessage());
            return null;
        }
    }
} 